// grass/pages/uploadnfo/uploadInfo.js
var common = require("../../../common/common.js").common;

var WxParse = require("../../../wxParse/wxParse.js");

var util = require("../../../utils/util.js");

var app = getApp();

Page({
    /**
   * 页面的初始数据
   */
    data: {
        id: "",
        type: "1",
        //1 图文 2 视频
        name: "",
        //标题
        introduction: "",
        //简介
        topic_id: "",
        //选择的话题
        topic_name: "",
        cateList: [],
        //分类
        cate_id: "",
        //选择的分类
        cate_name: "",
        chooseGoods: [],
        //选择的商品
        imageArr: [],
        //上传的图片
        video: "",
        //上传的视频
        cover_img: "",
        //视频上传的封面图
        ruleModal: false,
        draftsModals: false,
        animationData: {},
        //内容动画
        animationMask: {},
        //蒙板动画
        agreement: 1
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        let that = this;
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        wx.hideShareMenu();
        if (options.type) {
            that.setData({
                type: options.type
            });
        }
        if (options.id) {
            that.setData({
                id: options.id
            });
            that.getGrassDetail();
        }
        this.animateTrans = wx.createAnimation({
            duration: 600,
            timingFunction: "ease"
        });
        this.animateFade = wx.createAnimation({
            duration: 600,
            timingFunction: "ease"
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        let that = this;
        that.getCate();
        //获取分类
                that.getRule();
        //获取协议
                that.getAwardList();
        //获取奖励规则
        },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        let that = this;
        that.requestStart();
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    color_header: res.extra.color_header,
                    color_text: res.extra.color_text,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    style: res.extra.style
                });
            }
        });
    },
    /**
  * 获取规则
  */
    getAwardList: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/person/award_rule",
            method: "post",
            data: {},
            success: res => {
                that.setData({
                    awardList: res.extra
                });
            }
        });
    },
    //获取种草详情
    getGrassDetail: function() {
        let that = this;
        common.request({
            endpoint: "Plantgrass/list/grass_detail",
            method: "post",
            data: {
                id: that.data.id
            },
            success: res => {
                let details = res.extra;
                let imgs = [];
                if (details.type == 1 && details.img) {
                    let imgArr = details.img.split(",");
                    imgArr.map(x => {
                        imgs.push({
                            url: x
                        });
                    });
                }
                that.setData({
                    details: details,
                    name: details.name,
                    introduction: details.introduction,
                    topic_id: details.topic_id,
                    topic_name: details.topic_name,
                    cate_id: details.cate_id,
                    cate_name: details.cate_name,
                    type: details.type,
                    chooseGoods: details.pro_info,
                    imageArr: imgs,
                    video: details.video,
                    cover_img: details.cover_img
                });
            }
        });
    },
    //获取规则
    getRule: function() {
        var that = this;
        common.request({
            endpoint: "Plantgrass/manage/rule",
            method: "post",
            data: {},
            success: res => {
                if (!res.extra) {
                    res.extra = "<p>暂无协议</p>";
                }
                WxParse.wxParse("rule", "html", res.extra, that, 0);
            }
        });
    },
    //显示规则
    showRuleModal: function() {
        let that = this;
        that.setData({
            ruleModal: true
        });
    },
    //隐藏规则
    hideRuleModal: function() {
        let that = this;
        that.setData({
            ruleModal: false
        });
    },
    /**
   * 监听input变化
   */
    recordValue: function(e) {
        let key = e.currentTarget.dataset.name;
        let value = e.detail.value;
        this.setData({
            [key]: value
        });
    },
    //进入产品详情 判断权限 不可以合并吗
    goToDetail(e) {
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    //获取分类
    getCate: function() {
        var that = this;
        common.request({
            endpoint: "Plantgrass/manage/grass_cate",
            method: "post",
            data: {},
            success: res => {
                let cateList = res.extra.filter(x => {
                    return x.name != "全部";
                });
                that.setData({
                    cateList: cateList
                });
            }
        });
    },
    //选择分类
    bindCateChange: function(e) {
        let that = this;
        that.setData({
            cate_id: that.data.cateList[e.detail.value].id,
            cate_name: that.data.cateList[e.detail.value].name
        });
    },
    //移除该关联的商品
    removeGoods: function(e) {
        let that = this;
        let chooseGoods = that.data.chooseGoods;
        chooseGoods = chooseGoods.filter(item => {
            return item.id != e.currentTarget.dataset.id;
        });
        that.setData({
            chooseGoods: chooseGoods
        });
    },
    //上传图文
    uploadImage: function(e) {
        let that = this;
        let count;
        if (that.data.type == 1) {
            //图文可传多张
            let len = that.data.imageArr.length;
            count = 6 - len;
        } else {
            count = 1;
        }
        wx.chooseImage({
            count: count,
            sizeType: [ "original", "compressed" ],
            sourceType: [ "album", "camera" ],
            success(res) {
                const tempFilePaths = res.tempFilePaths;
                wx.showLoading({
                    title: "正在上传..."
                });
                var i = 0;
                var length = tempFilePaths.length;
                that.uploadFile(tempFilePaths, i);
            }
        });
    },
    //上传图片
    uploadFile: function(tempFilePath, i) {
        var that = this;
        let domain = app.globalData.domain.split("frontend")[0] + "backend" + app.globalData.domain.split("frontend")[1];
        wx.uploadFile({
            url: domain + "Imagesystem/img/saveimg",
            filePath: tempFilePath[i],
            name: "file",
            formData: {
                uniacid: wx.getStorageSync("uniacid"),
                esb: 3,
                img_type: "full"
            },
            headers: {
                "Content-Type": "multipart/form-data",
                uniacid: wx.getStorageSync("uniacid")
            },
            success(res) {
                let data = JSON.parse(res.data);
                if (that.data.type == 1) {
                    let imageArr = that.data.imageArr;
                    imageArr.push(data.extra.image[0]);
                    that.setData({
                        imageArr: imageArr
                    });
                } else {
                    that.setData({
                        cover_img: data.extra.image[0].url
                    });
                }
                i++;
                if (i < tempFilePath.length) {
                    that.uploadFile(tempFilePath, i);
                } else {
                    wx.hideLoading();
                }
            },
            fail: function(res) {
                wx.hideToast();
                wx.showModal({
                    title: "错误提示",
                    content: "上传图片失败",
                    showCancel: false,
                    success: function(res) {}
                });
            }
        });
    },
    //上传视频
    chooseVideo: function() {
        let that = this;
        wx.chooseVideo({
            sourceType: [ "album", "camera" ],
            maxDuration: 60,
            camera: "back",
            compressed: false,
            success(res) {
                let tempFilePath = res.tempFilePath;
                const version = wx.getSystemInfoSync().SDKVersion;
                //console.log(version);
                                if (util.compareVersion(version, " 2.11.0") > 0) {
                    wx.getVideoInfo({
                        src: tempFilePath,
                        success: function(res) {
                            if (res.size > 1024 * 20) {
                                wx.showModal({
                                    title: "提示",
                                    content: "视频超过20M，请重新选择！",
                                    showCancel: false
                                });
                                return false;
                            } else {
                                wx.showLoading({
                                    title: "正在上传..."
                                });
                                that.uploadVideo(tempFilePath);
                            }
                        },
                        fail(res) {
                            wx.showLoading({
                                title: "正在上传..."
                            });
                            that.uploadVideo(tempFilePath);
                        }
                    });
                } else {
                    wx.showLoading({
                        title: "正在上传..."
                    });
                    that.uploadVideo(tempFilePath);
                }
            },
            fail(res) {
                console.log(res);
            }
        });
    },
    uploadVideo: function(tempFilePath) {
        var that = this;
        let domain = app.globalData.domain.split("frontend")[0] + "frontend" + app.globalData.domain.split("frontend")[1];
        wx.uploadFile({
            url: domain + "Plantgrass/img/saveimg",
            filePath: tempFilePath,
            name: "file",
            formData: {
                uniacid: wx.getStorageSync("uniacid")
            },
            header: {
                "Content-Type": "multipart/form-data",
                uniacid: wx.getStorageSync("uniacid")
            },
            success(res) {
                that.setData({
                    video: JSON.parse(res.data).extra.image[0].url
                });
            },
            fail: function(res) {
                wx.hideToast();
                wx.showModal({
                    title: "错误提示",
                    content: "上传视频失败,视频超出内容限制!",
                    showCancel: false,
                    success: function(res) {}
                });
            },
            complete: function() {
                wx.hideLoading();
            }
        });
    },
    /**
   * 删除图片
   */
    deleteImage: function(e) {
        let that = this;
        let idx = e.currentTarget.dataset.currentindex;
        let imageArr = that.data.imageArr;
        imageArr.splice(idx, 1);
        that.setData({
            imageArr: imageArr
        });
    },
    /**
   * 删除视频封面
   */
    deleteCoverImage: function() {
        let that = this;
        that.setData({
            cover_img: ""
        });
    },
    /**
   * 删除视频
   */
    deleteVideo: function() {
        let that = this;
        that.setData({
            video: ""
        });
    },
    forSubmit: common.throttle(function(e) {
        let that = this;
        let play = "1";
        console.log("保存");
        that.publish(play);
    }, 3e3),
    //返回是否保存至草稿箱
    goBack: function() {
        let that = this;
        that.setData({
            draftsModals: true
        });
        that.showModal();
    },
    /**
   * 同意取消协议
   */
    agreementAction: function() {
        let that = this;
        that.setData({
            agreement: !that.data.agreement
        });
    },
    // 显示
    showModal: function() {
        this.animateTrans.translateY(0).step();
        this.animateFade.opacity(1).step();
        this.setData({
            draftsModals: true,
            animationData: this.animateTrans.export(),
            //动画实例的export方法导出动画数据传递给组件的animation属性
            animationMask: this.animateFade.export()
        });
    },
    // 隐藏
    hideModal: function() {
        let that = this;
        that.animateTrans.translateY(300).step();
        that.animateFade.opacity(0).step();
        that.setData({
            animationData: that.animateTrans.export(),
            animationMask: that.animateFade.export()
        });
        setTimeout(() => {
            that.setData({
                draftsModals: false
            });
        }, 500);
    },
    //返回上一页
    goBackAction: function() {
        wx.navigateBack({});
    },
    //保存至草稿箱
    saveDraft: function() {
        let that = this;
        let play = "2";
        that.publish(play);
    },
    /**
   * 发布
   * play 1 发布   2保存至草稿箱
   * type 1 图文   2视频
   */
    publish: function(play) {
        let that = this;
        if (!that.data.agreement) {
            wx.showModal({
                title: "提示",
                content: "请先阅读协议",
                showCancel: false
            });
            return;
        }
        if (!that.data.name) {
            wx.showModal({
                title: "提示",
                content: "请输入标题！",
                showCancel: false
            });
            return;
        }
        if (!that.data.introduction) {
            wx.showModal({
                title: "提示",
                content: "请输入简介！",
                showCancel: false
            });
            return;
        }
        if (!that.data.cate_id) {
            wx.showModal({
                title: "提示",
                content: "请输入种草分类！",
                showCancel: false
            });
            return;
        }
        if (that.data.type == 1 && !that.data.imageArr.length) {
            //图文
            wx.showModal({
                title: "提示",
                content: "请上传至少一张图片！",
                showCancel: false
            });
            return;
        } else if (that.data.type == 2) {
            if (!that.data.cover_img) {
                wx.showModal({
                    title: "提示",
                    content: "请上传封面图！",
                    showCancel: false
                });
                return;
            }
            if (!that.data.video) {
                wx.showModal({
                    title: "提示",
                    content: "请上传视频！",
                    showCancel: false
                });
                return;
            }
        }
        // if (!that.data.chooseGoods.length && play == 1){
        //   wx.showModal({
        //     title: '提示',
        //     content: '请选择关联商品！',
        //     showCancel: false,
        //   })
        //   return;
        // }
                let img = [];
        let pro_ids = [];
        that.data.imageArr.map(x => {
            img.push(x.url);
        });
        that.data.chooseGoods.map(x => {
            pro_ids.push(x.id);
        });
        var param = {
            name: that.data.name,
            introduction: that.data.introduction,
            topic_id: that.data.topic_id,
            cate_id: that.data.cate_id,
            pro_id: pro_ids.join(","),
            do: that.data.type == 1 ? "img" : "video"
        };
        if (play == 1) {
            param["play"] = "publish";
            //发布
                }
        if (that.data.type == 1) {
            //图文
            param["img"] = img.join(",");
        } else {
            param["cover_img"] = that.data.cover_img;
            param["video"] = that.data.video;
        }
        if (that.data.id) {
            param["id"] = that.data.id;
        }
        common.request({
            endpoint: "Plantgrass/manage/publish",
            method: "post",
            data: param,
            success: res => {
                wx.showModal({
                    title: "提示",
                    content: res.message,
                    showCancel: false,
                    success: function() {
                        wx.navigateBack({});
                    }
                });
            },
            fail(res) {
                wx.showModal({
                    title: "提示",
                    content: res.message,
                    showCancel: false,
                    success: function() {}
                });
            }
        });
    }
});